package com.util;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * This class provides a singleton implementation for database connections.
 * The connection object is never exposed by the api. The user always gets the
 * java.sql.Statement and java.sql.PreparedStatement using the helper methods
 * provided by this class.
 * 
 * @author singhgn
 * @version 1.0
 */
public class DBConnection {

	
	private static Connection con = null;
	private static Properties databaseProperties = new Properties();
	
	static{
		try {
			databaseProperties.load(DBConnection.class.getClassLoader().getResourceAsStream("vectorDB.properties"));
			Class.forName("com.sybase.jdbc3.jdbc.SybDriver").newInstance();
			Properties dbProps = new Properties();
			dbProps.put("user", databaseProperties.getProperty("user"));
			dbProps.put("password", databaseProperties.getProperty("password"));
			String dbURL="jdbc:sybase:Tds:"+databaseProperties.getProperty("server")+":"+databaseProperties.getProperty("port");
			con = DriverManager.getConnection(dbURL, dbProps);	
			System.out.println("dbconnection = "+con);
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	private DBConnection(){
	}
	
	private static Connection getConnection(){
		return con;
	}
	
	public static Statement getStatement() throws SQLException{
		return con.createStatement();
	}
	
	public static PreparedStatement getPreparedStatement(String sql) throws SQLException{
		return con.prepareStatement(sql);
	}
	/**
	 * The param objects can contain connection, statement and resultset.
	 * TODO:This is not yet implemented
	 * @param objects
	 */
	public static void freeConnection(Object...objects ){
		if(con!=null){
			try {
				con.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			con=null;
		}
	}
}
